package com.koalac.ironman.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class FileBaseHandle {
	protected File file;
	protected FileType type;

	protected FileBaseHandle () {
	}

	/** Creates a new absolute FileHandle for the file name. Use this for tools on the desktop that don't need any of the backends.
	 * Do not use this constructor in case you write something cross-platform. Use the {@link AmsFiles} interface instead.
	 * @param fileName the filename. */
	public FileBaseHandle (String fileName) {
		this.file = new File(fileName);
		this.type = FileType.Absolute;
	}

	/** Creates a new absolute FileHandle for the {@link File}. Use this for tools on the desktop that don't need any of the
	 * backends. Do not use this constructor in case you write something cross-platform. Use the {@link AmsFiles} interface instead.
	 * @param file the file. */
	public FileBaseHandle (File file) {
		this.file = file;
		this.type = FileType.Absolute;
	}

	protected FileBaseHandle (String fileName, FileType type) {
		this.type = type;
		file = new File(fileName);
	}

	protected FileBaseHandle (File file, FileType type) {
		this.file = file;
		this.type = type;
	}

	public String path () {
		return file.getPath();
	}

	public String name () {
		return file.getName();
	}
	
	public FileType type () {
		return type;
	}

	private File file () {
		//不使用外部卡等文件//if (type == FileType.External) return new File(Gdx.files.getExternalStoragePath(), file.getPath());
		return file;
	}
	
	/** Returns a stream for reading this file.
	 * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
	public InputStream read () {
		if (type == FileType.Classpath || (type == FileType.AssetsType && !file.exists())) {
			InputStream input = FileBaseHandle.class.getResourceAsStream("/" + file.getPath().replace('\\', '/'));
			if (input == null) throw new RuntimeException("File not found: " + file + " (" + type + ")");
			return input;
		}
		try {
			return new FileInputStream(file());
		} catch (FileNotFoundException ex) {
			if (file().isDirectory())
				throw new RuntimeException("Cannot open a stream to a directory: " + file + " (" + type + ")", ex);
			throw new RuntimeException("Error reading file: " + file + " (" + type + ")", ex);
		}
	}

}
